<template>
  <div>
    <p class="pinformation" style="margin-top: 7px">搜索条件</p>
    <el-form label-width="100px" :model="queryParams" ref="queryRef">
      <el-row>
        <el-col :span="4">
          <el-form-item label="报告编号：" prop="reportCode">
            <el-input v-model="queryParams.reportCode" clearable maxlength="100" @keyup.enter="handeleQuery"
              placeholder="请输入报告编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报告名称：" prop="reportName">
            <el-input v-model="queryParams.reportName" clearable maxlength="100" @keyup.enter="handeleQuery"
              placeholder="请输入报告名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="委托单位：" prop="wtCustomName">
            <el-input v-model="queryParams.wtCustomName" clearable maxlength="100" @keyup.enter="handeleQuery"
              placeholder="请输入委托单位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="委托单位：" prop="wtCustomName">
            <el-input v-model="queryParams.wtCustomName" clearable maxlength="100" @keyup.enter="handeleQuery"
              placeholder="请输入委托单位"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报告类型：" prop="reportType">
            <el-select v-model="queryParams.reportType" placeholder="请选择报告类型">
              <el-option v-for="dict in report_type" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-row justify="center">
            <el-button type="success" @click="handeleQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-form-item label="方案编号：" prop="projectCode">
            <el-input v-model="queryParams.projectCode" clearable maxlength="100" @keyup.enter="handeleQuery"
              placeholder="请输入方案编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="报告模板：" prop="templateId">
            <el-select v-model="queryParams.templateId" placeholder="请选择报告模板" clearable filterable style="width: 100%">
              <el-option v-for="item in templateList" :key="item.templateId" :label="item.templateName"
                :value="item.templateId" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- ！ -->
        <el-col :span="4">
          <!-- planDate -->
          <el-form-item label="编制时间：">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" :clearable="false"
              :editable="false" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否打印：" prop="isPrint">
            <el-select v-model="queryParams.isPrint" placeholder="请选择是否打印" filterable style="width: 100%">
              <el-option v-for="item in printList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <p class="pinformation">
        {{ props.isOut == 1 ? "未" : "已" }}发放报告列表
      </p>
      <p class="totalStyle">共 {{ total }} 条数据</p>
      <!-- <el-button link @click="handleDistri" :disabled="!reportIds.length"
        style="padding-bottom: 7px;margin-left: 15px;">批量发放</el-button> -->
    </el-row>
    <el-table ref="mainTableRef" :data="projectList" v-loading="loading" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="reportCode" label="报告编号" align="center" width="120" />
      <el-table-column prop="reportName" label="报告名称" align="center" />
      <el-table-column prop="wtCustomName" label="委托单位" align="center" />
      <el-table-column prop="sjCustomName" label="受检单位" align="center" />
      <el-table-column prop="projectCode" label="方案编号" align="center" width="160" />
      <el-table-column prop="createTime" label="编制时间" align="center" width="160" />
      <el-table-column label="审核状态" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.isOut == 2">待审核</span>
          <span v-if="scope.row.isOut == 3">已审核</span>
        </template>
      </el-table-column>
      <el-table-column prop="isPrint" label="是否打印" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.isPrint == 0">未打印</span>
          <span v-else>已打印</span>
        </template>
      </el-table-column>
      <el-table-column prop label="操作" align="center" width="250">

        <template #default="scope">
          <el-button link type="success" @click="handleAchvieFile(scope.row)" v-if="!scope.row.fileId">生成存档文件</el-button>
          <template v-if="scope.row.fileId">
          <el-button link type="success" @click="handlePrintFile(scope.row)"
            v-if="scope.row.isPrint == 0">打印</el-button>
          <el-button link type="success" @click="handlePrintFile(scope.row)"
            v-if="scope.row.isPrint == 1">重新打印</el-button>
          <el-button link type="success" @click="handleViewFile(scope.row)">查看</el-button>
          <el-button link type="success" @click="viewOutTable(scope.row)">发放表</el-button>
          <el-button link type="success" @click="handleDownload(scope.row)">下载</el-button>
          <el-button link type="success" v-if="props.isOut == 1" @click="handleDistri(scope.row)">发放</el-button>
        </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="handeleQuery" />
    <el-dialog :class="'el-dialog-theme3'" v-model="outShow" fullscreen title="查看报告发放表">
      <record :isHide="true" ref="recordRef"></record>
    </el-dialog>
  </div>
</template>

<script setup>
import record from "../../../flowable/task/record/index.vue";
import { getGrantList } from "@/api/projectArchive/index";
import {
  taskIdByProcId
} from "@/api/flowable/todo";
import { getTemplateList, addReportPrintRecord,createAchvieFile } from "@/api/report/reportProject";
import { getLatestProcess } from "@/api/common";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { blobValidate } from "@/utils/ruoyi";
const { proxy } = getCurrentInstance();
const router = useRouter();
const { report_type } = proxy.useDict("report_type");
const projectList = ref([]);
const total = ref(0);
const dateRange = ref([]);
const loading = ref(false)
const outShow = ref(false);
const recordRef = ref(null)
const routeViewStore = useRouteView();
import useRouteView from "@/store/modules/routeView";

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    isPrint: ''
  },
});
const { queryParams, form } = toRefs(data);
const props = defineProps({
  isOut: {
    type: Number, //参数类型
  },
});

function handeleQuery() {
  queryParams.value.isOut = props.isOut;
  loading.value = true
  getGrantList(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false
      projectList.value = res.rows;
      total.value = res.total;
    }
  );
}

function handleDistri(row) {
  if (row.outProcInsId && row.isOut == 1) {
    taskIdByProcId(row.outProcInsId).then(res => {
      if (routeViewStore.routeView1) {
        proxy.$tab.closePage(routeViewStore.routeView1);
      }
      router.push({
        path: "/flowable/task/record/index",
        query: {
          taskId: res.data,
          finished: true,
          path: "/index",
        },
      });
    });
    return;
  }
  proxy.$modal.confirm("确定要发放吗？").then(() => {
    proxy.$modal.loading("正在启动流程中，请稍候...");
    let id = row.reportId || reportIds.value
    getLatestProcess({ category: "14" }).then((res) => {
      proxy.$modal.closeLoading();
      if (res.data) {
        proxy.$tab.closePage().then(() => {
          router.push({
            path: "/flowable/task/record/index",
            query: {
              deployId: res.data.deploymentId,
              finished: true,
              path: "/report/reportDistribution",
              v_reportId: id
            },
          });
        });
      } else {
        proxy.$modal.msgError("流程启动失败，未到找到相关流程！");
      }
    });
  })
}

function handleDownload(row) {
  proxy.$modal.loading("正在下载文件，请稍候...");
  proxy.$download.localFile(row.fileId, row.filePath).then((res) => {
    proxy.$modal.closeLoading();
  });
}

function handleAchvieFile(row){
  createAchvieFile(row.reportId).then((res) => {
    proxy.$modal.msgSuccess(res.msg);
  });
}
function handlePrintFile(row) {
  proxy.$modal.loading("正在加载，请稍候...");
  const url =
    import.meta.env.VITE_APP_BASE_API + "/system/file/download/" + row.fileId;
  axios({
    method: "get",
    url: url,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  }).then(async (res) => {
    const isLogin = await blobValidate(res.data);
    if (isLogin) {
      const blob = new Blob([res.data]);
      const file = new File([blob], "document.pdf", {
        type: "application/pdf",
      });
      addReportPrintRecord(row.reportId).then(res => {
        const url = URL.createObjectURL(file);
        proxy.$modal.closeLoading();
        window.open(url);
        row.isPrint = 1;
      }).catch(e => {
        proxy.$modal.closeLoading();
      });
    }
  });
}
function viewOutTable(row) {
  outShow.value = true
  nextTick(() => {
    recordRef.value.getInfo(row.outProcInsId)
  })
}
function handleViewFile(row) {
  proxy.$modal.loading("正在加载，请稍候...");
  const url =
    import.meta.env.VITE_APP_BASE_API + "/system/file/download/" + row.fileId;
  axios({
    method: "get",
    url: url,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  }).then(async (res) => {
    const isLogin = await blobValidate(res.data);
    if (isLogin) {
      const blob = new Blob([res.data]);
      const file = new File([blob], "document.pdf", {
        type: "application/pdf",
      });
      const url = URL.createObjectURL(file);
      proxy.$modal.closeLoading();
      window.open(url);
    }
  });
}

function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handeleQuery();
}

defineExpose({
  getTableHeight,
});

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 22 }];
    }
    getTableHeight();
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 22 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
handeleQuery();

const templateList = ref([]);
getTemplateList().then((res) => {
  templateList.value = res.data;
});

const printList = ref([
  { id: "", name: "不限" },
  { id: "0", name: "未打印" },
  { id: "1", name: "已打印" },
]);


const reportIds = ref([])

function handleSelectionChange(selection) {
  reportIds.value = selection.map(item => item.reportId).join(",");
}
</script>

<style></style>
